package com.demo;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * 下载流流向: 获取图片连接的输入流->文件输出流，相对内存来说，从网络输入到内存，然后从内存输出到文件
 *
 */
public class GetFileFromNetURL {
    public static void main(String[] args) throws IOException {

        //网络图片URL
        String imageURL = "https://www.baidu.com/img/bd_logo.png";
        String saveImagePath = System.getProperty("user.dir") + "/netURL/target/bd_logo.png";

        System.out.println(System.getProperty("user.dir"));
        URL url = new URL(imageURL);
        //打开网络连接
        URLConnection connection = url.openConnection();
        //获取输入流
        InputStream inputStream = connection.getInputStream();
        //输出文件流
        OutputStream outputStream = new FileOutputStream(new File(saveImagePath));
        //缓冲区对象
        byte[] b = new byte[1024];
        int len;//读取计数器
        while ((len = inputStream.read(b)) != -1) {
            outputStream.write(b, 0, len);
        }
        try {
            //关闭输入流
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //关闭输出流
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
